from django.shortcuts import render
from dwebsocket.decorators import accept_websocket, require_websocket
from django.http import HttpResponse
import subprocess
from django_demo import settings


@accept_websocket
def echo_once(request):
  if not request.is_websocket():  # 判断是不是websocket连接
    try:  # 如果是普通的http方法
      message = request.GET['message']
      return HttpResponse(message)
    except:
      return render(request, 'index.html')
  else:
    for message in request.websocket:
      message = message.decode('utf-8')  # 接收前端发来的数据
      print(message)
      if message == 'backup_all':  # 这里根据web页面获取的值进行对应的操作
        cmd = 'bash '+ settings.BASE_DIR+'/tbash.sh'  # 这里是要执行的命令或者脚本
        p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1)
        #lines = []
        # 循环发送消息给前端页面
        for line in iter(p.stdout.readline, b''):
          line = line.strip().decode("utf8")
          print('-->',line)
          request.websocket.send(line)  # 发送消息到客户端
          if not subprocess.Popen.poll(p) is None:
            if line == "":
              print("break")
              break
        p.stdout.close()
        p.wait()
      else:
        request.websocket.send('小样儿，没权限!!!'.encode('utf-8'))
